<template>
  <div class="question-management">
    <h1>原始问题管理</h1>
    
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-inputs">
        <input v-model="searchParams.title" placeholder="输入问题标题" />
        <input :value="searchParams.version" placeholder="版本号缺失" disabled/>
        <button @click="handleSearch()">搜索</button>
      </div>
    </div>

    <!-- 结果表格 -->
    <div class="results-table" v-if="searchResults.length > 0">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>标题</th>
            <!-- <th>版本</th> -->
          </tr>
        </thead>
        <tbody>
          <tr 
            v-for="item in searchResults" 
            :key="item.id"
            @click="goToQuestionDetail(item)"
            class="clickable-row"
          >
            <td>{{ item.id }}</td>
            <td>{{ item.title }}</td>
            <!-- <td>{{ item.version }}</td> -->
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加问题按钮已移除 -->

    <!-- 百度风格分页组件 -->
    <div class="baidu-pagination" v-if="searchResults.length > 0">
      <div class="pagination-container">
        <span 
          class="page-btn prev" 
          :class="{ disabled: pagination.currentPage <= 1 }"
          @click="pagination.currentPage > 1 ? handleSearch(pagination.currentPage - 1) : null"
        >
          <span class="arrow">←</span> 上一页
        </span>
        
        <span
          v-for="page in getDisplayPages()"
          :key="page"
          class="page-number"
          :class="{ 
            active: pagination.currentPage === page,
            ellipsis: page === '...'
          }"
          @click="typeof page === 'number' && handleSearch(page)"
        >
          {{ page }}
        </span>
        
        <span 
          class="page-btn next" 
          :class="{ disabled: pagination.currentPage * pagination.pageSize >= pagination.total }"
          @click="pagination.currentPage * pagination.pageSize < pagination.total ? handleSearch(pagination.currentPage + 1) : null"
        >
          下一页 <span class="arrow">→</span>
        </span>
      </div>
    </div>

    <!-- 添加问题弹窗已移除 -->
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useVersionStore } from '@/stores/versionStore'
import { countSearchResults, searchOriginalQuestions, type OriginalQuestion } from '@/api/question'

export default defineComponent({
  name: 'QuestionManagement',
  setup() {
    
    const versionStore = useVersionStore()

    // 搜索相关逻辑
    const searchParams = ref({
      title: '',
      version: versionStore.currentVersion?.ver_code || ''
    })
    const searchResults = ref<OriginalQuestion[]>([])
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    const handleSearch = async (page = 1) => {
      try {
        pagination.value.currentPage = page
        const results = await searchOriginalQuestions({
          title: searchParams.value.title,
          version: searchParams.value.version,
          page: page - 1, // 后端从0开始
          size: pagination.value.pageSize
        })
        searchResults.value = results
        pagination.value.total = await countSearchResults({
          title: searchParams.value.title,
          version: searchParams.value.version
        }) // 假设API返回的结果中包含总数
        console.log('搜索结果:', results)
      } catch (error) {
        console.error('搜索失败:', error)
      }
    }

    const router = useRouter()

    const goToQuestionDetail = (question: OriginalQuestion) => {
      router.push({
        name: 'questionDetail',
        params: {
          id: question.id,
          version: versionStore.currentVersion?.ver_code || question.version || 'v1.0',
          title: encodeURIComponent(question.title),
          content: encodeURIComponent(question.content),
          source: question.source || '',
          time: question.updateTime || new Date().toISOString(),
          active: question.active !== undefined ? question.active : true
        }
      })
    }

    // 获取显示的页码数组(带省略号)
    const getDisplayPages = () => {
      const totalPages = Math.ceil(pagination.value.total / pagination.value.pageSize)
      console.log('搜索结果数:', pagination.value.total)
      const current = pagination.value.currentPage
      const range = 2 // 当前页前后显示的页码数
      const pages = []
      
      if (totalPages <= 7) {
        for (let i = 1; i <= totalPages; i++) {
          pages.push(i)
        }
        console.log('总页数小于等于7，直接返回所有页码:', pages)
        return pages
      }
      
      // 添加前几页
      for (let i = 1; i <= 3; i++) {
        pages.push(i)
      }
      
      // 添加省略号或中间页码
      if (current > range + 3) {
        pages.push('...')
      }
      
      // 添加当前页附近的页码
      const start = Math.max(4, current - range)
      const end = Math.min(totalPages - 1, current + range)
      for (let i = start; i <= end; i++) {
        if (!pages.includes(i)) pages.push(i)
      }
      
      // 添加省略号或最后几页
      if (current < totalPages - range - 2) {
        pages.push('...')
      }
      
      // 添加最后几页
      for (let i = totalPages - 2; i <= totalPages; i++) {
        if (!pages.includes(i)) pages.push(i)
      }
      
      return pages
    }

    // 初始化时执行默认搜索
    handleSearch()

    return {
      searchParams,
      searchResults,
      handleSearch,
      goToQuestionDetail,
      pagination,
      getDisplayPages
    }
  }
})
</script>

<style scoped>
.question-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.actions {
  margin: 20px 0;
}

.actions {
  margin: 20px 0;
}

.actions button {
  margin-right: 10px;
  padding: 8px 16px;
  background-color: #2c3e50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.actions button:hover {
  background-color: #1a252f;
}

/* 百度风格分页样式 */
.baidu-pagination {
  margin: 30px 0;
  text-align: center;
}

.pagination-container {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  display: inline-block;
  padding: 0 12px;
  height: 34px;
  line-height: 34px;
  color: #333;
  cursor: pointer;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  background: #fff;
  font-size: 14px;
}

.page-btn:hover:not(.disabled) {
  color: #315efb;
  border-color: #315efb;
}

.page-btn.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.page-btn .arrow {
  font-weight: bold;
}

.page-number {
  display: inline-block;
  min-width: 34px;
  height: 34px;
  line-height: 34px;
  color: #333;
  cursor: pointer;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  background: #fff;
  text-align: center;
  font-size: 14px;
}

.page-number:hover:not(.active):not(.ellipsis) {
  color: #315efb;
  border-color: #315efb;
}

.page-number.active {
  color: #fff;
  background-color: #315efb;
  border-color: #315efb;
  cursor: default;
}

.page-number.ellipsis {
  border: none;
  background: transparent;
  cursor: default;
}

/* 弹窗相关样式已移除 */
/* 搜索区域样式 */
.search-area {
  margin: 20px 0;
}

.search-inputs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-inputs input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
}

.search-inputs button {
  padding: 8px 16px;
  background-color: #2c3e50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-inputs button:hover {
  background-color: #1a252f;
}

/* 结果表格样式 */
.results-table {
  margin: 20px 0;
  overflow-x: auto;
}

.results-table table {
  width: 100%;
  border-collapse: collapse;
}

.results-table th,
.results-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.results-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.results-table tr:hover {
  background-color: #f9f9f9;
}

.clickable-row {
  cursor: pointer;
}

.clickable-row:hover {
  background-color: #e6f7ff !important;
}
</style>
